<?php



$input1 = "1.mp3";
$input2 = "2.mp3";
$input3 = "3.mp3";
$input4 = "4.mp3";
$input5 = "5.mp3";
$input6 = "6.mp3";

$output = "output.mp3";

$dir = '../google_tts/mp3_tts/';

$mp3 = new MP3Splitter();
$files = $mp3->findFiles($dir);
$aData = $mp3->readFiles($files);
$data = $mp3->splitFilesData($aData);
$mp3->saveData($output, $data);
exit();









class MP3Splitter
{
	
	
	
	public function findFiles($dir)
	{
		$dh = opendir($dir);
		$aFiles = array();
		while(false !== ($file = readdir($dh)))
		{
			if($file != "." && $file != "..")
			{
				$aFiles[] = $dir.$file;
			}
		}
		closedir($dh);
		return $aFiles;
	}
	
	public function readFiles($files)
	{
		$aData = array();
		foreach($files as $key => $file)
		{
			$fh = fopen($file, 'r');
			
			if($key != 0)
			{
				fseek($fh, -128, SEEK_END);
	        	$rawTag = fread($fh, 128);
	        	
	        	$format = "";
	        	if ($rawTag[125] == chr(0) && $rawTag[126] != chr(0))
	        	{
		            $format = 'a3marking/a30title/a30artist/a30album/a4year'
		                    . '/a28comment/x1/C1track/C1genre';
		        }
		        else
		        {
		            $format = 'a3marking/a30title/a30artist/a30album/a4year'
		                    . '/a30comment/C1genre';
		        }
		        	
	        	
				$tags = unpack($format, $rawTag);
			}
			
//			print_r($tags); exit();
			
//			$tags = fread($fh, 128);
//			fseek($fh, -128, SEEK_END);
			$fdata = "";
			while(true)
			{
				$fd = fread($fh, 1024);
				if(!$fd)
				{
					break;
				}
				$fdata .= $fd;
			}
			fclose($fh);
			$aData[] = $fdata;
		}
		return $aData;
	}
	
	public function splitFilesData($aData)
	{
		$data = "";
		foreach($aData as $key => $val)
		{
			$tmp = $val;
			$tmp = $this->_cutHeader($tmp);
//			echo $tmp;
			$data .= $tmp;
		}
		return $data;
	}
	
	private function _cutHeader($fl)
	{
	    $Header = substr($fl,0,10);
	    $tagLen = $this->_calcDecTagLen(substr($Header,6,4));
//	    echo $tagLen; 
	    $music = substr($fl,$tagLen+10,-128);
//	    echo $music; 
//        $tagLen = 1024; 
//        $Header = substr($Header,0,6).setHexTagLen($tagLen);
		return $music;
	}
	
	private function _calcDecTagLen($word) 
	{ 
	    $m = 1; 
	    $int = 0; 
	    for ($i=strlen($word)-1;$i>-1;$i--) {
//	    	echo ord($word[$i])."    "; 
	        $int += $m * ord($word[$i]);//  
	        $m=$m*128;
//	        echo $m."<br />"; 
        } 
	    return $int; 
    } 
	
	
	
	public function saveData($fileOutput, $data)
	{
		$fh = fopen($fileOutput, 'w+');
		$tags = fwrite($fh, $data);
		fclose($fh);
	}
	
}



?>